<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="用户权限管理">
        页面数据为 Mock 示例数据，非真实数据。
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" >
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    {{checkedKeys}}
    <n-modal v-model:show="menusShowModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          cascade
          checkable
          :virtual-scroll="true"
          :data="treeData"
          :check-strategy="'parent'"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h, onMounted } from 'vue';
  import { useDialog, useMessage } from "naive-ui";
  import { BasicTable, TableAction } from '@/components/Table';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { getTreeAll } from '@/utils';
  import { useRouter } from 'vue-router';
  import { deleteById, getUserList, updatePermissionsById } from "@/api/system/user";
  import { ResultEnum } from "@/enums/httpEnum";
  import { getMenuList } from "@/api/system/menu";

  const router = useRouter();
  // const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const menusShowModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedAll = ref(false);
  const editRoleTitle = ref('');
  const treeData = ref([]);
  const expandedKeys = ref([]);
  const checkedKeys = ref([]);
  const dialog = useDialog();

  const params = reactive({
    pageSize: 5,
    name: null
  });

  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '菜单权限',
            onClick: handleMenuAuth.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['sys:role:update'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            auth: ['sys:role:update'],
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['sys:role:delete'],
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };

    let { data } = await getUserList(_params);
    return data;
  };

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    console.log("e", e)

    updatePermissionsById(currentUserId.value, checkedKeys.value).then((data) => {
      formBtnLoading.value = false;
      message.success('修改成功');
      menusShowModal.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    // router.push({ name: 'basic-info', params: { id: record.id } });
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除此权限吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        deleteById(record.id).then(res => {
          if(res.code == ResultEnum.SUCCESS) {
            message.success('删除成功');
          }
        });
      },
      onNegativeClick: () => {
        message.error('已取消');
      },
    });
    message.info('点击了删除');
  }

  const currentUserId = ref(null);

  function handleMenuAuth(record: Recordable) {
    editRoleTitle.value = `分配 ${record.name} 的菜单权限`;
    checkedKeys.value = record.menus;
    currentUserId.value = record.id;

    console.log('record', record)
    menusShowModal.value = true;
  }

  function checkedTree(keys) {
    checkedKeys.value = [];
    checkedKeys.value = [...keys];

  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = treeData.value.map((item: any) => item.name) as [];
    }
  }

  function checkedAllHandle() {
    if (!checkedAll.value) {
      checkedKeys.value = getTreeAll(treeData.value);
      checkedAll.value = true;
    } else {
      checkedKeys.value = [];
      checkedAll.value = false;
    }
  }

  // 选中: 点击那一栏
  function selectedTree(keys) {
    console.log('点击选中的那一栏', keys)
  }

  onMounted(async () => {
    const treeMenuList = await getMenuList();
    console.log('treeMenuList', treeMenuList)
    expandedKeys.value = treeMenuList.map((item) => item.id);
    // treeData.value = treeMenuList;
    treeData.value = [];
    treeMenuList.forEach((t) => {
      // 二级菜单处理
      if (t.children && t.children.length != 0) {
        let childrenMenuList = t.children;
        let tempList = [];
        childrenMenuList.forEach((c) => {


          tempList.push({...c, label: c.name, key: c.name, isLeaf: c.children.length <= 0});
        });
        t.children = tempList;
      }

      treeData.value.push({...t, label: t.name, key: t.name,isLeaf: t.children.length <= 0});
    });
  });

</script>

<style lang="less" scoped></style>
